import { useState, useRef, useEffect } from 'react'
import { Wrapper } from './FileBlob.styled'

const pickerOpts = {
  types: [
    {
      description: 'Images',
      accept: {
        'image/*': ['.png', '.gif', '.jpeg', '.jpg']
      }
    },
  ],
  excludeAcceptAllOption: true,
  multiple: false
};

export const Demo = () => {
  const refCanvas = useRef<any>(null)
  const [objUrl, setObjUrl] = useState<any>(null)
  const [context, setContext] = useState<any>(null)

  useEffect(() => {
    const ctx = refCanvas.current?.getContext("2d");
    if (!!ctx) setContext(ctx);
  })

  const color2Gray = (imgData: ImageData) => {
    for (let index=0, i=0;i<imgData.width;i++) {
      for (let j=0;j<imgData.height;j++,index+=4) {
        const red   = imgData.data[index];
        const green = imgData.data[index+1];
        const blue  = imgData.data[index+2];
        
        const ave   = (red+green+blue)/3;
        
        imgData.data[index]   = ave;
        imgData.data[index+1] = ave;
        imgData.data[index+2] = ave;
      }
    }
  }
  const onOpen = async () => {
    const [filehandle] = await (window as any).showOpenFilePicker(pickerOpts);
    const f = await filehandle.getFile()
    const url = URL.createObjectURL(f)
    setObjUrl(url)

    const image = new Image()
    image.width = 100;
    image.onload = () => {
      context.drawImage(image, 0, 0, 100, 100)
      const data = context.getImageData(0, 0, 100, 100)
      color2Gray(data);
      context.putImageData(data, 0, 0, 0, 0, data.width, data.height)
    }
    image.src = url
  }
  const save = async (handle:any) => {
    if (!handle) return;
    const stream = await handle.createWritable();
    refCanvas.current.toBlob(async (b:Blob) => {
      if (!b) return;
      await stream.write(b);
      await stream.close();
    })
  }
  const onSave = async (e:any) => {
    e.preventDefault();
    const filehandle = await (window as any).showSaveFilePicker();
    save(filehandle)
  }

  return (
    <Wrapper>
      { !!objUrl &&
        <>
        <img src={objUrl} width={300} alt="img" />
        <br />
        </>
      }
      <canvas ref={refCanvas} width="100" height="100">
        !!! This browser doesn't support canvas !!!
      </canvas>
      <br />
      <div>
        <button onClick={onOpen}>open</button>
        <button onClick={onSave}>save</button>
      </div>
    </Wrapper>
  )
}
